export default class Base64Util {

    /**
     * @param { string } str
     */
    static encode(str) {
        return window.btoa(encodeURIComponent(str));
    }

    /**
     * @param { string } base64Str
     */
    static decode(base64Str) {
        return decodeURIComponent(window.atob(base64Str));
    }

    /**
     * @param { string } base64Str
     */
    static toBlob(base64Str) {
        const byteString = atob(base64Str.split(',')[1]);
        const mimeString = base64Str.split(',')[0].split(':')[1].split(';')[0];
        const ab = new ArrayBuffer(byteString.length);
        const ia = new Uint8Array(ab);
        for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        return new Blob([ab], { type: mimeString });
    }

    /**
     * @param { Blob } blob
     * @return { Promise<string> }
     */
     static parseBlob(blob) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader()
            // @ts-ignore
            reader.onload = function(e) { resolve(e.target.result) };
            reader.onerror = function () { reject(new Error("转换失败")) };
            reader.readAsDataURL(blob)
        });
    }

    /**
     * @param { string } base64Str
     */
    static toImage(base64Str) {
        return new Promise((resolve, reject) => {
            const image = new Image();
            image.src = base64Str;
            image.onload = function () { resolve(image) };
            image.onerror = function () { reject(new Error("转换失败")) };
        });
    }

}
